//
//  LXUrgingRentListViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/1/6.
//  Copyright © 2022 LX_App. All rights reserved.
//

#import "LXUrgingRentListViewController.h"
#import "LXSignTableViewCell.h"
#import "LXSignContractApplyViewController.h"
#import "LXSignContractModel.h"
#import "LXCarStockListViewController.h"
#import "LXRescindViewController.h"
#import "LXDatePickView.h"
#import "LXSignContractDetailViewController.h"
@interface LXUrgingRentListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSInteger pageIndex;
@property (nonatomic) UIView *topView;
@property (nonatomic) NSString *timeStartStr,*timeEndStr;
@property (nonatomic) UIButton *timeBtn1, *timeBtn2;
@property (nonatomic) BOOL isChoose;
/**底部view*/
@property (nonatomic) UIView *bottomView;
/**催租ids*/
@property (nonatomic) NSMutableArray *ids;
/**已选择*/
@property (nonatomic) UILabel *lab1;
/**选择按钮*/
@property (nonatomic) UIButton *rightButton;
@end

@implementation LXUrgingRentListViewController



- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor colorWithHexString:@"#FAFBFC"];

    [self layoutCustomNav:self.view title:@"一键催租"];
    
    self.ids = [NSMutableArray array];
    
    self.pageIndex = 1;
    
    [self loadData];
    
    [self setUIView];

    [self.view addSubview:self.tableView];
    
    
    [self layoutBottomView];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXSignTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXSignTableViewCell class])];
    
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageIndex = 1;
        [self loadData];
    }];

   
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
         self.pageIndex++;
        [self loadData];
    }];
    
   
    
}
//MARK: 底部view
-(void)layoutBottomView{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight + 100, kScreenWidth, 60)];
    bottomView.backgroundColor = UIColor.whiteColor;
    self.bottomView = bottomView;
    [self.view addSubview:bottomView];
    
    UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 70, 20)];
    lab1.text = @"已选择(0)";
    lab1.textColor = Color333;
    lab1.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:lab1];
    self.lab1 = lab1;
    
    UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 115, 10, 100, 40)];
    btn1.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn1 setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn1 setBackgroundColor:mainColor];
    [btn1 setTitle:@"催租" forState:UIControlStateNormal];
    [btn1 addCorner:3];
    [bottomView addSubview:btn1];
    
    [btn1 whenTapped:^{
        if (ObjectIsEmpty(self.ids)){
            showAlert(@"请选择至少一辆车");
            return;
        }
        [self saveRent];
    }];
    
    
}
//MARK: 催租
-(void)saveRent{
    
    
    [Tool showAlertTitle:[NSString stringWithFormat:@"确认对%@辆车催租?",@(self.ids.count)] msg:@"催租成功今日将无法再次催租" cancelTitle:@"我再想想" commitBtnTitle:@"确认催租" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
//        NSString *url = [DOMAIN_URL stringByAppendingFormat:POST_PostsignSave];
        NSString *json = [NSString toJSONData:self.ids];
        [MSNetworkManager postRevertUrl:POST_PostsignSave params:@{@"ids":json} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
    
            if (isSuccess) {
        
                showAlert(@"催租成功");
                self.isChoose = NO;
                self.pageIndex = 1;
                [self.ids removeAllObjects];
                self.lab1.text = @"已选择(0)";
                self.rightButton.selected = NO;
                self.tableView.contentInset =  UIEdgeInsetsMake(0,0,0,0);
                self.bottomView.Y = kScreenHeight + 100;
                [self loadData];
                
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
    
}
//MARK: 顶部view
- (void)setUIView{
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 70, KStatuesBarHeight, 60, 30)];
   rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
   [rightButton setTitle:@"选择" forState:UIControlStateNormal];
    [rightButton setTitle:@"取消" forState:UIControlStateSelected];
   [rightButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [rightButton setBackgroundColor:mainColor];
    [rightButton addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton addCorner:3];
    self.rightButton = rightButton;
   [self.view addSubview:rightButton];
    
    
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, 50)];
    topView.backgroundColor = UIColor.clearColor;
    self.topView = topView;
    [self.view addSubview:topView];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 85, 50)];
    lab.text = @"选择交租日";
    lab.textColor = Color333;
    lab.font = [UIFont systemFontOfSize:15];
    [topView addSubview:lab];
    
    
    
    
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(lab.X_width, 10, 104, 30);
    btn1.backgroundColor = ColorWithF5F5F5;
    [btn1 addCorner:3];
    btn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn1.titleLabel.font = [UIFont systemFontOfSize:12];
    [btn1 setTitleColor:ColorWithAAAAAA forState:UIControlStateNormal];
    [btn1 setTitleColor:ColorWith333333 forState:UIControlStateSelected];
    [btn1 setTitle:@"开始日期" forState:UIControlStateNormal];
    [btn1 setImage:[UIImage imageNamed:@"acc_down"] forState:UIControlStateNormal];
    [btn1 setImage:[UIImage imageNamed:@"acc_downSelect"] forState:UIControlStateSelected];
    [topView addSubview:btn1];
    [btn1 setIconInRightWithSpacing:10];
    self.timeBtn1 = btn1;
    [btn1 whenTapped:^{
        [self clickStartTime];
    }];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(btn1.X_width + 5, btn1.centerY, 15, 1)];
    line.backgroundColor = ColorWithAAAAAA;
    [topView addSubview:line];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(line.X_width + 5, 10, 104, 30);
    btn2.backgroundColor = ColorWithF5F5F5;
    [btn2 addCorner:3];
    btn2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn2.titleLabel.font = [UIFont systemFontOfSize:12];
    [btn2 setTitleColor:ColorWithAAAAAA forState:UIControlStateNormal];
    [btn2 setTitleColor:ColorWith333333 forState:UIControlStateSelected];
    [btn2 setTitle:@"结束日期" forState:UIControlStateNormal];
    [btn2 setImage:[UIImage imageNamed:@"acc_down"] forState:UIControlStateNormal];
    [btn2 setImage:[UIImage imageNamed:@"acc_downSelect"] forState:UIControlStateSelected];
    [topView addSubview:btn2];
    [btn2 setIconInRightWithSpacing:10];
    self.timeBtn2 = btn2;
    [btn2 whenTapped:^{
        [self clickEndTime];
    }];
    
  
    UIButton *btn3 = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 40, 0, 30, 50)];
    btn3.titleLabel.font = [UIFont systemFontOfSize:12];
    [btn3 setTitleColor:mainColor forState:UIControlStateNormal];
    [btn3 setTitle:@"重置" forState:UIControlStateNormal];
    [topView addSubview:btn3];
    
    [btn3 whenTapped:^{
        btn1.selected = NO;
        btn2.selected = NO;
        [btn1 setIconInRightWithSpacing:10];
        [btn2 setIconInRightWithSpacing:10];
        self.timeStartStr = @"";
        self.timeEndStr = @"";
        self.pageIndex = 1;
        [self loadData];
    }];
    
}

- (void)loadData{
    
    NSString *url = [DOMAIN_URL stringByAppendingFormat:SigncontractPage_URL];
    
    
    
    NSMutableDictionary *dic = @{
        @"page":@(self.pageIndex),
        @"rows":@(10),
        @"type":@(4),
        @"signStatus":@(1)
    }.mutableCopy;
    if (!StringIsEmpty(self.timeStartStr)) {
        [dic setValue:self.timeStartStr forKey:@"beginPayDate"];
    }
    if (!StringIsEmpty(self.timeEndStr)) {
        [dic setValue:self.timeEndStr forKey:@"endPayDate"];
    }
    
    
    [MSNetworkManager getRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
            
            if ([self.tableView.mj_header isRefreshing]||self.pageIndex==1) {
                [self.data removeAllObjects];
                [self.tableView.mj_footer resetNoMoreData];
            }
            NSInteger totalPage = [resonseObj[@"total"] integerValue];
            
            NSArray *records = resonseObj[@"records"];
            
            [self.data addObjectsFromArray:[LXSignContractModel  mj_objectArrayWithKeyValuesArray:records]];
            
            
            if (self.data.count>=totalPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
            
          
            [self.tableView reloadData];
            
        }
        
       
        
        [self isHaveEmptyData];
        [self endRefreshing];
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self endRefreshing];
        [self isHaveEmptyData];
    } withShowHud:YES];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LXSignTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXSignTableViewCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    LXSignContractModel *model = self.data[indexPath.section];
    cell.signModel = model;
    cell.label9.hidden = YES;
    cell.label10.hidden = YES;
    cell.label11.hidden = YES;
    cell.label12.hidden = NO;
    
    if (self.isChoose) {
        cell.leftCons.constant = 35;
    }
    else {
        cell.leftCons.constant = 10;
    }
    if (model.remindPayRentStatus == 1) {
        [cell.chooseBtn setImage:[UIImage imageNamed:@"不可选"] forState:UIControlStateNormal];
        cell.chooseBtn.selected = NO;
    }
    else {
        
        
        cell.chooseBtn.selected = model.isSel;
        
        if(model.isSel == 1){
            [cell.chooseBtn setImage:[UIImage imageNamed:@"设置性别已选择"] forState:UIControlStateNormal];
        }
        else {
            [cell.chooseBtn setImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateNormal];
        }
    }
    
    [cell setClickBtnAction:^(UIButton * _Nonnull sender) {
        if (sender.isSelected) {
            [self.ids addObject:model.signContractId];
        }
        else {
            [self.ids removeObject:model.signContractId];
        }
        self.lab1.text = [NSString stringWithFormat:@"已选择(%@)",@(self.ids.count)];
    }];
    
    
//    [cell.chooseBtn whenTapped:^{
//        if (model.remindPayRentStatus == 1) return;
//        model.isSel = !cell.chooseBtn.isSelected;
////        cell.chooseBtn.selected = !cell.chooseBtn.isSelected;
//
//        if (cell.chooseBtn.isSelected) {
//            [self.ids addObject:model.signContractId];
//        }
//        else {
//            [self.ids removeObject:model.signContractId];
//        }
//        self.lab1.text = [NSString stringWithFormat:@"已选择(%@)",@(self.ids.count)];
//
//    }];

    
    
    
    if (model.remindPayRentStatus==1) {
        cell.label12.backgroundColor = [ColorWith3C6CFC colorWithAlphaComponent:0.1];
        cell.label12.textColor = ColorWith3C6CFC;
        cell.label12.text = @"已催租";
    }
    else {
        cell.label12.backgroundColor = [[UIColor colorWithHexString:@"#FF921C"] colorWithAlphaComponent:0.1];
        cell.label12.textColor = [UIColor colorWithHexString:@"#FF921C"];
        cell.label12.text = @"未催租";
    }
    
    return cell;
}

    
    
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    vv.backgroundColor = [UIColor colorWithHexString:@"#FAFBFC"];
    return vv;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    if (self.isChoose) {
         LXSignTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        LXSignContractModel *model = self.data[indexPath.section];
        if (!cell.chooseBtn.isSelected) {
            [self.ids addObject:model.signContractId];
            cell.chooseBtn.selected = YES;
            [cell.chooseBtn setImage:[UIImage imageNamed:@"设置性别已选择"] forState:UIControlStateNormal];
        }
        else {
            [self.ids removeObject:model.signContractId];
            cell.chooseBtn.selected = NO;
            [cell.chooseBtn setImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateNormal];
            
        }
        model.isSel = cell.chooseBtn.isSelected;
        self.lab1.text = [NSString stringWithFormat:@"已选择(%@)",@(self.ids.count)];
        
        
//        [cell setClickBtnAction:^(UIButton * _Nonnull sender) {
//            if (cell.chooseBtn.isSelected) {
//                [self.ids addObject:model.signContractId];
//            }
//            else {
//                [self.ids removeObject:model.signContractId];
//            }
//            self.lab1.text = [NSString stringWithFormat:@"已选择(%@)",@(self.ids.count)];
//        }];
    }
    else {
        LXSignContractDetailViewController *vc = [[LXSignContractDetailViewController alloc] init];
        vc.signContractModel = self.data[indexPath.section];
        vc.fromVc = NSStringFromClass([self class]);
        [self pushToNextController:vc];
    }
   
    
    
    
    
}





- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.Y_height, kScreenWidth, kScreenHeight - self.topView.Y_height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 120;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#FAFBFC"];
        _tableView.tableFooterView = [UIView new];
        _tableView.sectionFooterHeight = 10;
//        _tableView.contentInset =  UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (void)isHaveEmptyData{
    if (self.data.count == 0) {
        self.tableView.startTip = YES;
        self.tableView.tipView.backgroundColor = self.tableView.backgroundColor;
        self.tableView.tipImage = [UIImage imageNamed:@"No_order_icon"];
        self.tableView.tipView.hidden = NO;
        self.tableView.scrollEnabled = YES;
    }else{
        self.tableView.tipView.hidden = YES;
        self.tableView.scrollEnabled = YES;
    }
}


- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}
-(void)clickBtn:(UIButton *)sender{
    self.isChoose = !self.isChoose;
    sender.selected = self.isChoose;
    
    if (sender.isSelected) {
        [UIView animateWithDuration:0.2 animations:^{
            self.bottomView.Y = kScreenHeight - 60;
            self.tableView.contentInset =  UIEdgeInsetsMake(0,0,kComHeight + 10,0);

        }];
    }
    else {
        [UIView animateWithDuration:0.2 animations:^{
            self.bottomView.Y = kScreenHeight + 100;
            self.tableView.contentInset =  UIEdgeInsetsMake(0,0,0,0);

        }];
        
    }
    
    
    [self.tableView reloadData];
    
    
}
#pragma mark -- 选择开始日期
-(void)clickStartTime{
    [self.view endEditing:YES];
    LXDatePickView *datePicker =[[LXDatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.timeStartStr withIsMaxDate:YES withNoForward:NO WithTips:@"请选择开始日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    
    datePicker.block = ^(NSString *yearString){
        if([NSString compareDate:self.timeEndStr withDate:yearString withFormat:k_DateFormat]==1){
            self.timeStartStr  = [NSString getNowDateWithFormat:@"yyyy-MM-dd"];
            showAlert(@"开始日期不能大于结束日期");
        }
        else {
            self.timeStartStr = yearString;
            [self.timeBtn1 setTitle:[NSString stringWithFormat:@"%@",self.timeStartStr] forState:UIControlStateSelected];
            self.timeBtn1.selected = YES;
            [self.timeBtn1 setIconInRightWithSpacing:10];
            
            self.pageIndex = 1;
            [self loadData];
        }
     
    };
}
#pragma mark -- 选择日期
-(void)clickEndTime{
    [self.view endEditing:YES];
    LXDatePickView *datePicker =[[LXDatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.timeEndStr withIsMaxDate:YES withNoForward:NO WithTips:@"请选择结束日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    datePicker.cancelBlock = ^(NSString *yearString) {
        self.timeStartStr  = @"";
    };
    datePicker.block = ^(NSString *yearString){
        if([NSString compareDate:yearString withDate:self.timeStartStr withFormat:k_DateFormat]==1){
            self.timeStartStr  = [NSString getNowDateWithFormat:@"yyyy-MM-dd"];
            showAlert(@"结束日期不能小于开始日期");
        }
        else {
            self.timeEndStr = yearString;
            [self.timeBtn2 setTitle:[NSString stringWithFormat:@"%@",self.timeEndStr] forState:UIControlStateSelected];
            self.timeBtn2.selected = YES;
            [self.timeBtn2 setIconInRightWithSpacing:10];
            self.pageIndex = 1;
            [self loadData];
        }
        
    };
}

@end
